import React, {useEffect, useState} from "react";
import {Dimensions, StyleSheet, View, Text, TouchableHighlight} from "react-native";
import {getWalletInfo} from "./smartxL2Libs/L2_Data";
import {ethers} from "ethers";
import LinearProgress from "react-native-elements/dist/linearProgress/LinearProgress";
import {fontSize_12, fontSize_13, fontSize_15, fontSize_16, fontSize_20} from "./theme";
import {Tab} from "react-native-elements/dist/tab/Tab";
import {TabView} from "react-native-elements";
import {setCopyMsg} from "../libs/utils";
import QRCode from "react-native-qrcode-svg";
import {SvgXml} from "react-native-svg";
import {closeEye2SvgXml} from "../libs/svgXml";

const {width,height,scale} = Dimensions.get("window");

const L2_KeystoreView = ({navigation,route}:any) => {
    const [address,setAddress] = useState(route?.params?.address)
    const [chainID,setChainID] = useState(route?.params?.chainID)
    const [keystore,setKeystore] = useState("")
    const [progress,setProgress] = useState(0)
    const [showProgress,setShowProgress] = useState(false)
    //Keystore文件或者二维码
    const [index,setIndex] = useState(0)
    //提示文字
    const [tipContent,setTipContent] = useState([
        {
            index:0,
            title:"离线保存",
            content:"请复制粘贴 Keystore 文件到安全、离线的地方保存。切勿保存至邮箱、记事本、网盘、聊天工具等，非常危险"
        },
        {
            index:0,
            title:"请勿使用网络传输",
            content:"请勿通过网络工具传输 Keystore 文件，一旦被黑客获取将造成不可挽回的资产损失。建议离线设备通过扫二维码方式传输"
        },
        {
            index:0,
            title:"密码保险箱保存",
            content:"如需在线保存，则建议使用安全等级更高的1Password 等密码保管软件保存 Keystore"
        },
        {
            index:1,
            title:"仅供直接扫描",
            content:"二维码禁止保存、截图、以及拍照。仅供用户在安全环境下直接扫描来方便地导入钱包"
        },
        {
            index:1,
            title:"在安全环境下使用",
            content:"请在确保四周无人及无摄像头的情况下使用。二维码一旦被他人获取将造成无可挽回的资产损失。"
        },
    ])
    const [showCode,setShowCode] = useState(false)
    useEffect(()=>{
        navigation.setOptions({
            title:"导出Keystore"
        })
        initKeystore();
    },[])
    const initKeystore = async () => {
        let wallet = await getWalletInfo(chainID,address)
        if(!keystore && wallet)
        {
            setShowProgress(true)
            setTimeout(async ()=>{
                let keystoreTemp = await getKeyStore(wallet.privateKey,wallet.password);
                setKeystore(keystoreTemp)
            },0)
        }
    }
    const getKeyStore = async (key:string,password:string) => {
        try {
            // 回调函数可以获取导出进度
            function callback(percent: any) {
                console.log(showProgress)
                console.log("Encrypting: " + parseInt((percent * 100).toString()) + "% complete");
                setProgress(parseInt((percent * 100).toString()))
            }
            let wallet = new ethers.Wallet(key);
            let json = await wallet.encrypt(password, callback);
            console.log(json)
            return json;
        }catch (e) {
            console.log(`getKeyStoreError:${e}`)
            return "";
        }finally {
            setShowProgress(false)
        }
    }
    return (
        <View style={styles.container}>
            {
                showProgress?
                    <View style={{flex:1,width:width,alignItems:"center",padding:40,paddingTop:150,backgroundColor:"rgba(0,0,0,0.2)"}}>
                        <Text style={{color:"#03dac4",fontSize:fontSize_15,lineHeight:40}}>正在加载Keystore... {progress}% </Text>
                        <LinearProgress color="#03dac4" trackColor={"#9af0e7"} value={progress/100} variant="determinate"/>
                    </View>
                    :
                    <View style={{flex:1,width:"100%"}}>
                        <Tab value={index} onChange={setIndex} indicatorStyle={styles.tabIndicatorStyle}>
                            <Tab.Item title="Keystore 文件"
                                      background={null}
                                      buttonStyle={{padding: 0, margin: 0}}
                                      containerStyle={{backgroundColor: "white"}}
                                      titleProps={{
                                          style: {
                                              padding: 0,
                                              // marginLeft: -25,
                                              color: index===0?"#0a65d6":"#707070",
                                              fontSize: fontSize_13,
                                              lineHeight: 40
                                          }
                                      }} />
                            <Tab.Item title="二维码"
                                      background={null}
                                      buttonStyle={{padding: 0, margin: 0}}
                                      containerStyle={{backgroundColor: "white"}}
                                      titleProps={{
                                          style: {
                                              padding: 0,
                                              color: index===1?"#0a65d6":"#707070",
                                              fontSize: fontSize_13,
                                              lineHeight: 40
                                          }
                                      }}
                            />
                        </Tab>
                        <View style={{flex:1,overflow:"hidden"}}>
                            <TabView value={index} animationType={"spring"}>
                                <TabView.Item style={{width:"100%",flex:1}}>
                                    <View style={{flex:1}}>
                                        {
                                            tipContent.length?
                                                tipContent.map((item,index_tipContent)=>(
                                                    item.index===index?
                                                        <View style={{width:"100%"}}>
                                                            <Text style={styles.tipContentTitle}>
                                                                {item.title}
                                                            </Text>
                                                            <Text style={styles.tipContentContent}>
                                                                {item.content}
                                                            </Text>
                                                        </View>
                                                        :null
                                                ))
                                                :null
                                        }
                                        <Text style={styles.KeysotreText}>{keystore}</Text>
                                        <TouchableHighlight
                                            underlayColor={"#1f83fd"}
                                            onPress={()=>{
                                                setCopyMsg(keystore)
                                            }}
                                            style={styles.AllLineBTN}
                                        >
                                            <Text style={styles.AllLineBTNTitle}>复制</Text>

                                        </TouchableHighlight>
                                    </View>
                                </TabView.Item>
                                <TabView.Item style={{width:"100%",flex:1}}>
                                    <View style={{flex:1}}>
                                        {
                                            tipContent.length?
                                                tipContent.map((item,index_tipContent)=>(
                                                    item.index===index?
                                                        <View style={{width:"100%"}}>
                                                            <Text style={styles.tipContentTitle}>
                                                                {item.title}
                                                            </Text>
                                                            <Text style={styles.tipContentContent}>
                                                                {item.content}
                                                            </Text>
                                                        </View>
                                                        :null
                                                ))
                                                :null
                                        }
                                        <View style={styles.QRcodeContainer}>
                                            <TouchableHighlight underlayColor={"white"} style={{padding:10,backgroundColor:"white"}}
                                                                onPress={()=>{
                                                                    setShowCode(!showCode)
                                                                }}
                                            >
                                                {
                                                    showCode?
                                                        <QRCode value={keystore}  size={190} />
                                                        :
                                                        <View style={styles.showCodeView}>
                                                            <SvgXml xml={closeEye2SvgXml("#97989a")} width={60} height={60}/>
                                                            <Text style={styles.showCodeViewTitle}>点击展示 Keystore 二维码</Text>
                                                        </View>
                                                }

                                            </TouchableHighlight>
                                        </View>
                                    </View>
                                </TabView.Item>
                            </TabView>
                        </View>

                    </View>
            }
        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: "white"
    },
    tabIndicatorStyle: {
        height: 2,
        backgroundColor: "#076ff5",
        width: "50%",
    },
    tipContentTitle:{
        fontSize:fontSize_16,
        // fontWeight:"bold",
        color:"#076ff5",
        lineHeight:35,
        marginTop:10
    },
    tipContentContent:{
        fontSize:fontSize_13,
        color:"#7a7a7a"
    },
    KeysotreText:{
        width:"100%",
        backgroundColor:"#f5f6f8",
        color:"#6c6d6f",
        marginTop:20,
        padding:5,
        fontSize:fontSize_12,
        marginBottom:10,
    },
    AllLineBTN:{
        width:"100%",
        height:40,
        backgroundColor:"#1f83fd",
        justifyContent:"center",
        alignItems:"center",
        borderRadius:5,
        marginTop:10,
        marginBottom:10
    },
    AllLineBTNTitle:{
        fontSize:fontSize_16,
        color:"white",
    },
    QRcodeContainer:{
        padding:10,
        marginTop:20,
        marginBottom:30,
        backgroundColor:"#e8f0fa",
        borderRadius:20,
        alignSelf:"center"
    },
    showCodeView:{
        width:190,
        height:190,
        backgroundColor:"#f5f6f8",
        alignItems:"center",
        justifyContent:"center"
    },
    showCodeViewTitle:{
        fontSize:fontSize_15,
        color:"#9c9d9f",
        marginTop:10
        // letterSpacing:0.5
    },

})
export default L2_KeystoreView;


